package com.heima.exam.p8;

import com.heima.exam.p8.MyAnno;
import com.heima.exam.p8.Sporter;
import com.heima.exam.p8.Student;
import com.heima.exam.p8.Teacher;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;

public class Demo1 {
    public static void main(String[] args) throws DocumentException, ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        SAXReader reader = new SAXReader();
        Document document = reader.read("src/com/heima/exam/p8/data.xml");
        Element rootElement = document.getRootElement();
        List<Element> elements = rootElement.elements();
        ArrayList<String> nameArr = new ArrayList<>();
        for (Element element : elements) {
            String className = element.attributeValue("className");
            nameArr.add(className);
        }
        String[] array = nameArr.toArray(new String[3]);
        String s = array[0];
        String s1 = array[1];
        String s2 = array[2];
        Class<?> stuClass = Class.forName(s);
        Class<?> teaClass = Class.forName(s1);
        Class<?> spoClass = Class.forName(s2);

        Constructor<?> stuConstructor = stuClass.getConstructor(String.class, int.class);
        Constructor<?> teaConstructor = teaClass.getConstructor(String.class, int.class);
        Constructor<?> spoConstructor = spoClass.getConstructor(String.class, int.class);

        Element[] elementsArr = elements.toArray(new Element[3]);
        if (stuClass.isAnnotationPresent(MyAnno.class)) {
            String name = elementsArr[0].elementText("name");
            String age = elementsArr[0].elementText("age");
            Student student = (Student) stuConstructor.newInstance(name, Integer.parseInt(age));
            System.out.println(student);
        }
        if (teaClass.isAnnotationPresent(MyAnno.class)) {
            String tname = elementsArr[1].elementText("name");
            String tage = elementsArr[1].elementText("age");
            Teacher teacher = (Teacher) teaConstructor.newInstance(tname, Integer.parseInt(tage));
            System.out.println(teacher);
        }
        if (spoClass.isAnnotationPresent(MyAnno.class)) {
            String sname = elementsArr[2].elementText("name");
            String sage = elementsArr[2].elementText("age");
            Sporter sporter = (Sporter) spoConstructor.newInstance(sname, Integer.parseInt(sage));
            System.out.println(sporter);
        }
    }
}